//
//  PostViewController.swift
//  ColorNote
//
//  Created by 伏文东 on 2018/2/10.
//  Copyright © 2018年 伏文东. All rights reserved.
//

import UIKit

class PostViewController: UIViewController {

    // MARK: - 控件属性
    @IBOutlet weak var textView: UITextView!
    @IBOutlet weak var textViewBouttonmCons: NSLayoutConstraint!
    // MARK: - 定义属性
    var callBackText : ((String) -> ())?
    var contentText: String?
    var inquire: Int64? // 查询timstamp
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(keybordChanged),
                                               name: NSNotification.Name.UIKeyboardWillChangeFrame,
                                               object: nil)
    }
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        textView.resignFirstResponder()
    }

    // MARK: 监听方法
    @objc private func clickCancel() {
        dismiss(animated: true, completion: nil)
    }
    
    @objc private func clickSave() {
        if textView.text.isEmpty {
            dismiss(animated: true, completion: nil)
            return
        }
        if callBackText != nil {
            callBackText!(textView.text!)
            if CoreDataManager.sharedManager.updata(timeStamp: inquire!, contentText: textView.text) {
                print("修改成功")
            }
        } else {
            if CoreDataManager.sharedManager.add(contentText: textView.text) {
                print("保存成功")
            }
        }
        
        dismiss(animated: true, completion: nil)
    }
    @objc private func keybordChanged(n: Notification) {
        guard let rect = (n.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue,
            let duartion = (n.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue else { return }
        print(rect)
        
        let offset = view.bounds.height - rect.origin.y + 64
        
        self.textViewBouttonmCons.constant = offset
        UIView.animate(withDuration: duartion) {
            self.view.layoutIfNeeded()
        }
    }
}

// MARK: - 设置UI界面
private extension PostViewController {
    func setupUI()  {
        setupNavi()
        if let contentText = contentText {
            textView.text = contentText
        }
    }
    func setupNavi()  {
        navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(clickCancel))
        navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .save, target: self, action: #selector(clickSave))
    }
}

























